import React, {
  forwardRef,
  useContext,
  useState,
  useImperativeHandle,
} from 'react'
import FormContext from '../Store/FormStore'
import useForm from '../Store/useForm'

// 状态管理
const Form = (
  {
    form, // form 是控制器
    onFinish,
    onFinishFailed,
    initialValues,
    children,
  },
  ref,
) => {
  const [formInstance] = useForm(form, initialValues)
  // setCallback, dispatch 这两个方法不能对外使用,所以要使用forword+ref来禁止掉
  const { setCallback, dispatch, ...providerFormInstance } = formInstance

  // 讲成功\失败方法 注册到回调函数中
  const Fun = (v) => v
  setCallback({
    onFinish: onFinish || Fun,
    onFinishFailed: onFinishFailed || Fun,
  })

  // ref 只能拿到除了setCallback,dispatch以外的方法
  useImperativeHandle(ref, () => providerFormInstance, [])

  const RenderChildren = (
    <FormContext.Provider value={formInstance}>{children}</FormContext.Provider>
  )

  return (
    <form
      onReset={(e) => {
        e.preventDefault()
        e.stopPropagation()
        formInstance.resetFields() /* 重置表单 */
      }}
      onSubmit={(e) => {
        e.preventDefault()
        e.stopPropagation()
        formInstance.submit() /* 提交表单 */
      }}
    >
      {RenderChildren}
    </form>
  )
}

// forwardRef 限制用户
export default forwardRef(Form)
